import 'package:flutter/material.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/widget/elder_header_image_cell.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/a_yyt/widget/home_my_work_view.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/utils.dart';

class ElderInfoPage extends StatefulWidget {
  final int? customerId;
  ElderInfoPage({Key? key,this.customerId});
  @override
  _ElderInfoPageState createState() => _ElderInfoPageState();
}

class _ElderInfoPageState extends State<ElderInfoPage> {
  ElderInfo? elderModel;
  int? _headimageId;
  @override
  void initState() {
    _headimageId = 0;
    e.eventBus.on(Constant.eventElderInfoSave, (arg) {
      _fectData();
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    super.initState();
  }

  @override
  void dispose() {
    e.eventBus.off(Constant.eventElderInfoSave);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String _name = '';
    String _birthDay = '';
    String _avoidThing = '';
    String _healthName = '';
    String _specialDiseaseRemark = '';
    if (elderModel != null) {
      _name = elderModel?.name??"" ;
      if (elderModel?.birthday != null) {
        _birthDay = elderModel!.birthday!.split(' ').first;
      }
      _avoidThing = elderModel?.avoidThing??"" ;
      _healthName = elderModel?.healthName ??"";
      _specialDiseaseRemark = elderModel?.specialDiseaseRemark??"";
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('长者信息'),
        elevation: 0.5,
        actions: [
          InkWell(
            onTap: () {
              _fectData(lastId: elderModel?.lastId, nextId: null);
            },
            child: Icon(
              Icons.arrow_left,
              size: 50,
            ),
          ),
          InkWell(
            onTap: () {
              _fectData(lastId: null, nextId: elderModel?.nextId);
            },
            child: Icon(
              Icons.arrow_right,
              size: 50,
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: elderModel==null?Container(): Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            ElderHeaderImageCell(
              info: elderModel!,
              headimageId: _headimageId!,
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16,vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: '身体状况：',
                          style: TextStyles.textDark14,
                        ),
                        TextSpan(
                            text: '$_healthName', style: TextStyles.textGray14)
                      ])),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: '生日：',
                          style: TextStyles.textDark14,
                        ),
                        TextSpan(
                            text: '$_birthDay', style: TextStyles.textGray14)
                      ])),
                    ],
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: '忌讳：',
                      style: TextStyles.textDark14,
                    ),
                    TextSpan(text: '$_avoidThing', style: TextStyles.textGray14)
                  ])),
                  SizedBox(
                    height: 8,
                  ),

                  Text.rich(TextSpan(children: [
                    TextSpan(
                      text: '病史：',
                      style: TextStyles.textDark14,
                    ),
                    TextSpan(
                        text: '$_specialDiseaseRemark',
                        style: TextStyles.textGray14)
                  ])),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    '紧急联系人',
                    style: TextStyles.textBoldDark14,
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  elderModel != null
                      ? Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: (elderModel?.familyList??[]).map((e) {
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 8.0),
                        child: GestureDetector(child: Text(
                          '${e.name}（${e.relationshipName}）  ${e.mobile}',
                          style: TextStyles.textDark14,
                        ),onTap: (){
                          if((e.mobile??'').isEmpty){
                            return;
                          }
                          Utils.launchTelURL(e.mobile??"");

                        },),
                      );
                    }).toList(),
                  )
                      : Container(),
                ],
              ),
            ),
            Container(
              color: Colours.bg_color,
              height: 5,
              width: double.infinity,
            ),
            _titleItem('信息查询'),
            MyWorkView(
              type: 4,
              info: elderModel!,
            ),
            _titleItem('操作'),
            elderModel != null
                ? MyWorkView(
                    type: 5,
                    elderNameLike: _name,
                    customerId: elderModel!.id!,
                    info: elderModel!,
                  )
                : Container(),
            // MyWorkView(
            //   type: 6,
            //   info: elderModel,
            //   elderNameLike: _name,
            // ),
          ],
        ),
      ),
    );
  }

  Widget _titleItem(String title) {
    return Padding(
      padding: EdgeInsets.all(15),
      child: Text(
        title,
        style: TextStyles.textBoldDark18,
      ),
    );
  }

  _fectData({int? lastId, int? nextId}) {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    int? _customerId = widget.customerId;
    if (lastId != null && lastId > 0) {
      _customerId = lastId;
    } else if (nextId != null && nextId > 0) {
      _customerId = nextId;
    }
    var map = {"customerId": _customerId};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.customerDetail, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ElderInfo model = ElderInfo.fromJson(map['data']);
            setState(() {
              elderModel = model;
              _headimageId = model.headimageId??0;
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      Toast.show(NetErrorUtils.getNetError(e));
    });
  }
}
